package question.solution3;

import question.SolutionTemplate;

import java.util.HashMap;
import java.util.Map;

public class Solution3 implements SolutionTemplate {

    public int lengthOfLongestSubstring(String s) {
        if(s.length()<=1){
            return s.length();
        }
        int pLeft = 0;
        int pRight = 1;
        int maxLength = 1;
        Map<Character, Integer> characterPositionMap = new HashMap<>();
        characterPositionMap.put(s.charAt(pLeft), 0);
        while(pRight < s.length()){
            char newChar = s.charAt(pRight);
            Integer existPosition = characterPositionMap.get(newChar);
            if(existPosition != null && existPosition >= pLeft){
                int length = pRight - pLeft;
                if(length > maxLength){
                    maxLength = length;
                }
                pLeft = existPosition+1;
            }
            characterPositionMap.put(newChar, pRight);
            pRight++;
        }

        int length = pRight - pLeft;
        if(length > maxLength){
            maxLength = length;
        }

        return maxLength;
    }

    @Override
    public void test() {
        int result = lengthOfLongestSubstring("abba");
        System.out.println(result);
    }

}
